<template>
  <vab-card class="authorization" shadow="hover" skeleton>
    <template #header>
      <vab-icon icon="bar-chart-2-line" />
      近七日交易额
      <el-tag class="card-header-tag" type="warning">日</el-tag>
    </template>
    <vab-chart
      :init-options="initOptions"
      :option="option"
      theme="vab-echarts-theme"
    />
    <div class="bottom">
      <span>
        日均交易:
        <vab-count
          :decimals="countConfig.decimals"
          :duration="countConfig.duration"
          :end-val="countConfig.endVal"
          :prefix="countConfig.prefix"
          :separator="countConfig.separator"
          :start-val="countConfig.startVal"
          :suffix="countConfig.suffix"
        />
        元
      </span>
    </div>
  </vab-card>
</template>

<script>
  import {
    defineComponent,
    onUnmounted,
    onMounted,
    reactive,
    toRefs,
  } from 'vue'
  import VabChart from '@/extra/VabChart'
  import VabCount from '@/extra/VabCount'
  import { getMoneyOfWeek } from '@/api/echartsApi'

  export default defineComponent({
    components: {
      VabChart,
      VabCount,
    },
    setup() {
      const state = reactive({
        timer: null,
        data: [10.2, 28, 100, 49, 28, 68, 75],
        countConfig: {
          startVal: 0,
          endVal: 0,
          decimals: 0,
          prefix: '',
          suffix: '',
          separator: ',',
          duration: 3000,
        },
        initOptions: {
          renderer: 'svg',
        },
        // 授权数
        option: {
          tooltip: {
            trigger: 'axis',
            extraCssText: 'z-index:1',
          },
          grid: {
            top: '5%',
            left: '0%',
            right: '5%',
            bottom: '0%',
            containLabel: true,
          },
          xAxis: [
            {
              type: 'category',
              data: ['0时', '4时', '8时', '12时', '16时', '20时', '24时'],
              axisTick: {
                alignWithLabel: true,
              },
            },
          ],
          yAxis: [
            {
              type: 'value',
            },
          ],
          series: [
            {
              name: '交易额',
              type: 'bar',
              barWidth: '60%',
              data: [10, 52, 20, 33, 39, 33, 22],
              itemStyle: {
                borderRadius: [2, 2, 0, 0],
                color: new VabChart.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  ['#88D1FF', '#1890FF'].map((color, offset) => ({
                    color,
                    offset,
                  }))
                ),
              },
            },
          ],
        },
      })

      onUnmounted(() => {
        state.timer = null
        clearInterval(state.timer)
      })
      const fetchData = async () => {
        const { data: datas } = await getMoneyOfWeek()
        state.data = datas
        //求7日平均
        let sum = 0
        state.data.forEach((it) => {
          sum += it
        })
        state.countConfig.endVal = parseFloat(sum / 7.0)

        let index = 0
        const base = +getDay(-7)
        const oneDay = 24 * 3600 * 1000
        const date = []
        //时间轴是一个一维空间，初始值是让他本身就有一个点，再加一条信息时就会长度为2，两点成线
        const data = [0]
        let now = new Date(base)
        const addData = (shift) => {
          now = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/')
          date.push(now)
          data.push(state.data[index++])
          if (shift) {
            //把初始值删了
            date.shift()
            data.shift()
          }
          now = new Date(+new Date(now) + oneDay)
        }
        for (let i = 0; i < 7; i++) {
          addData()
        }
        addData(true)
        state.option.xAxis[0].data = date
        state.option.series[0].data = data
      }
      onMounted(() => {
        fetchData()
      })

      const getDay = (day) => {
        var today = new Date()
        var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
        today.setTime(targetday_milliseconds) //注意，这行是关键代码
        var tYear = today.getFullYear()
        var tMonth = today.getMonth()
        var tDate = today.getDate()
        tMonth = doHandleMonth(tMonth)
        tDate = doHandleMonth(tDate)
        return new Date(tYear, tMonth, tDate)
      }
      //获取当前月份
      const doHandleMonth = (month) => {
        var m = month
        if (month.toString().length == 1) {
          m = '0' + month
        }
        return m
      }
      return {
        ...toRefs(state),
        doHandleMonth,
        getDay,
        fetchData,
      }
    },
  })
</script>
